package com.egg.action.common;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

/**
  * <p>Description: struts2的Action继承的基类</p>
  * @version 1.0
*/

public class BaseAction extends ActionSupport {

	private static final long serialVersionUID = -3407345311965834322L;

	private String targetPage;

	private String redirectUrl;

	/*
	 * Action使用的log,与log.xml内的名称对应
	 */
	protected Log log = LogFactory.getLog(getClass());
	/*
	 * 设置action的指向页面名称,不带后缀.各个具体Action在内部可以重写此方法,指定folder.
	 *
	 * @param folder
	 *
	 * @param targetPage
	 *
	 * @return
	 */
	protected String goPage(String folder, String targetPage) {
		this.targetPage = targetPage;
		return folder;
	}

	/**
	 *重定向
	 *
	 * @param pageActionName
	 * @param parameterStr
	 * @return
	 */
//	protected String goRedirectPage(String pageActionName, String parameterStr) {
//		this.redirectUrl = StringUtil.null2Trim(parameterStr).equals("") ? pageActionName : pageActionName + "?"
//				+ parameterStr;
//		return "redirect";
//	}

	/*
	 * 直接向Action的返回中写内容,多用于ajax返回或者直接的网络接口,默认字符集UTF-8
	 *
	 * @param str
	 *
	 * @throws IOException
	 */
	protected void write2Response(String str) {
		try {
			getResponse().setContentType("application/text; charset=GBK");
			getResponse().setHeader("Cache-Control", "no-cache");// 清楚缓存
			PrintWriter pw = getResponse().getWriter();
			pw.write(str);
			pw.close();
		} catch (IOException e) {
			log.error("写入response出错!原因:" + e.getMessage());
			e.printStackTrace();
		}
	}

	/*
	 * 得到当前应用的web路径
	 *
	 * @return
	 */
	protected String getBaseWebPath() {
		HttpServletRequest request = getRequest();
		String path = request.getContextPath();
		String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path
				+ "/";
		return basePath;
	}

	/**
	 *得到从来源的url,也就是从那个页面跳转到了当前页面
	 *
	 * @return
	 */
	protected String getFromUrl() {
		return getRequest().getHeader("Referer");
	}

	/**
	 *
	 *得到来源页面名称,带扩展名比如a.jsp
	 *
	 * @return
	 */
	protected String getFromPageName() {
		String fromUrl = getFromUrl();
		String pageName = fromUrl.substring(fromUrl.lastIndexOf("/") + 1);
		return pageName;
	}

	/**
	 *得到来源页面名称.不带扩展名
	 *
	 * @return
	 */
	protected String getFromPageNameNoEx() {
		String pageName = getFromPageName();
		pageName = pageName.substring(0, pageName.lastIndexOf("."));
		return pageName;
	}

	/**
	 *得到request所有的参数名称和参数值的对应map.key:参数名称,value:参数值
	 */
	protected Map<String, String> getParametersMap(String... excludeParams) {
		Map<String, String> map = new HashMap<String, String>();
		Enumeration<String> paramNames = getRequest().getParameterNames();
		while (paramNames.hasMoreElements()) {
			String paramName = paramNames.nextElement();
			String regex = "";
			for (int i = 0; i < excludeParams.length; i++) {
				regex = regex + excludeParams[i];
				if (i < excludeParams.length - 1)
					regex = regex + "|";
			}
			if (!paramName.matches(regex)) {
				String[] paramValues = getRequest().getParameterValues(paramName);
				if (paramValues.length == 1) {
					String paramValue = paramValues[0];
					try {
						paramValue = URLDecoder.decode(paramValue, "UTF-8");
					} catch (UnsupportedEncodingException e) {
					}
					if (paramValue.length() != 0)
						map.put(paramName, paramValue);
				} else {
					for (int i = 0; i < paramValues.length; i++) {
						try {
							String pv = URLDecoder.decode(paramValues[i], "UTF-8");
							if (pv.length() != 0)
								map.put(paramName + "[" + i + "]", pv);

						} catch (UnsupportedEncodingException e) {

						}
					}
				}
			}
		}
		return map;
	}

	/**
	 *得到request的所有参数字符串.不同参数之间用"&"连接.例如:name=gaojj&channelId=1
	 *
	 * @return
	 */
	protected String getParametersStr() {
		String ps = "";
		Map<String, String> pm = getParametersMap();
		for (Iterator<String> iter = pm.keySet().iterator(); iter.hasNext();) {
			String pName = iter.next();
			ps = ps + pName + "=" + pm.get(pName);
			if (iter.hasNext())
				ps = ps + "&";
		}
		return ps;
	}

	/**
	 *得到request所有的attribute对应map.key:attribute名称,value:attribute值
	 * @return
	 */
	protected Map<String, Object> getAttributeMap() {
		Map<String, Object> map = new HashMap<String, Object>();
		Enumeration<String> attributeNamea = getRequest().getAttributeNames();
		while (attributeNamea.hasMoreElements()) {
			String attributeName = attributeNamea.nextElement();
			Object attributeValue = getRequest().getAttribute(attributeName);
			if (attributeValue != null) {
				map.put(attributeName, attributeValue);
			}
		}
		return map;
	}

	/*
	 * 得到request
	 *
	 * @return
	 */
	protected HttpServletRequest getRequest() {
		return ServletActionContext.getRequest();
	}

	/*
	 * 得到response
	 *
	 * @return
	 */
	protected HttpServletResponse getResponse() {
		return ServletActionContext.getResponse();
	}

	/*
	 * 得到Session
	 *
	 * @return
	 */
	protected HttpSession getSession() {
		return ServletActionContext.getRequest().getSession();
	}

	/*
	 * 得到当前的上下文
	 *
	 * @return
	 */
	protected ServletContext getApplication() {
		return ServletActionContext.getServletContext();
	}

	/*
	 * @return the targetPage
	 */
	public String getTargetPage() {
		return targetPage;
	}

	/*
	 * @param targetPage the targetPage to set
	 */
	public void setTargetPage(String targetPage) {
		this.targetPage = targetPage;
	}

	public String getRedirectUrl() {
		return redirectUrl;
	}

	public void setRedirectUrl(String redirectUrl) {
		this.redirectUrl = redirectUrl;
	}


}